#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Comm.hpp"

class InetAddr
{
private:
    void NetPorttoHost()
    {
        _port = ntohs(_net_addr.sin_port);
    }
    void NetIptoHost()
    {
        char ipbuffer[64];
        const char *ip = inet_ntop(AF_INET, &_net_addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        (void)ip;
        _ip = ipbuffer;
    }
public:
    InetAddr()
    {}
    InetAddr(const struct sockaddr_in &addr)
        :_net_addr(addr)
    {
        NetPorttoHost();
        NetIptoHost();
    }
    InetAddr(uint16_t port)
        : _port(port)
        , _ip("")
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = htons(_port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }
    bool operator == (const InetAddr &addr)
    {
        return _ip == addr._ip;
    }
    struct sockaddr *NetAddr() {return CONV(&_net_addr);}
    socklen_t NetAddrLen() {return sizeof(_net_addr);}
    std::string Ip() const {return _ip;}
    uint16_t Port() const {return _port;}
    std::string Addr() const // 表示该成员函数不会修改类中的任何变量，可以被const对象调用
    {
        return Ip() + " " + std::to_string(Port());
    }
    void SetAddr(const sockaddr_in &client, socklen_t &len)
    {
        _net_addr = client;
        (void)len;
        NetIptoHost();
    }
    ~InetAddr()
    {}
private:
    struct sockaddr_in _net_addr;
    std::string _ip;
    uint16_t _port;
};
